package com.nanuminc.market.today.type;

import java.util.ArrayList;

import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.nanuminc.market.NMConstants;
import com.nanuminc.market.R;
import com.nanuminc.market.common.TimeLineAdapter;
import com.nanuminc.market.common.TimeLineList;
import com.nanuminc.market.today.TodayFullView_ngoc;
import com.nanuminc.market.today.TodayLocationCity_ngoc;
import com.nanuminc.market.today.TodayCategory;
import com.nanuminc.market.today.TodaySearch;
import com.nanuminc.market.today.detail.TodayDetailView_ngoc;
import com.nanuminc.market.utils.DomParserUtil;
import com.nanuminc.market.utils.ImageUtil;
import com.nanuminc.market.utils.XMLUtil;

public class TodayListAB_ngoc extends Activity implements OnClickListener {

	ArrayList<TimeLineList> arItem;
	//int totalListNum = 0;
	Context context;
	TimeLineAdapter myAdapter;
	ListView mainList;
	int UpdateFlag = 0;
	int itemNum = 0;
	String adType;
	public LinearLayout mAddView; //리스트에 더 불러올 때 로딩 표시하는 view
	private static final int DIALOG_LOCAL_AREA = 1;
	private static final int DIALOG_CATEGORY = 2;
	private static final int DIALOG_SEARCH = 3;
	int localPosition = 0, categoryPosition = 0;

	TextView title_left, title_right, title_center;
	String searchStr;
	String cate_selected;
	String loc_selected;
	// AB급
	// 카테고리 정의
	// Location 정의
	String mainListUrl_A;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.todaylist);

		context = getApplicationContext();
		// Timeline 리스트 호출
		createThreadAndDialog();
		mAddView = (LinearLayout) View.inflate(this, R.layout.addview, null); //로딩화면 객체화 후 inflate

		title_left = (TextView) findViewById(R.id.btn_location); //image 박아야 됨
		title_center = (TextView) findViewById(R.id.btn_title); //image 박아야 됨
		title_right = (TextView) findViewById(R.id.btn_search); //image 박아야 됨
		title_left.setOnClickListener(this); //리스트 안에서 OnClick에 반응하는 Listener set
		title_center.setOnClickListener(this);
		title_right.setOnClickListener(this);

		Intent intent = getIntent();
		adType = intent.getStringExtra("TYPE");
		
		Intent viewintent = new Intent(TodayListAB_ngoc.this, TodayFullView_ngoc.class);
		startActivity(viewintent);
	}

	/*private ProgressDialog loagindDialog;*/ // Loading Dialog

	void createThreadAndDialog() {
		/* ProgressDialog */
		/*loagindDialog = ProgressDialog.show(this, "로딩 중", "잠시만 기다려 주세요....",
				true, false);*/

		Thread thread = new Thread(new Runnable() {
			public void run() {
				// HttpPostTimeLine();
				arItem = new ArrayList<TimeLineList>();
				ImageUtil imgutil = new ImageUtil();
				NMConstants.totalListNum = 12; // test, DB 연동 필요									
	
				
				//
				
				
				if (NMConstants.totalListNum > 10) {
					for (itemNum = 0; itemNum < 10; itemNum++) {
						// imgutil.getPhoto(0, context,
						// thumbnailUrl_array.get(itemNum));
						// Bitmap bit = imgutil.mBit;
						Bitmap bit = BitmapFactory.decodeResource(
								getResources(), NMConstants.mImageIds[itemNum]); //Id를 가지고 Image Get
						
					/*	arItem.add(new TimeLineList(NMConstants.LIST_AB,
								restaurants[itemNum], message[itemNum], //add content
								"Distance : 3m", address[itemNum], bit, null, false)); */
						
						arItem.add(new TimeLineList(NMConstants.LIST_AB, //add content to TimelineList && DB 연동 필요
								NMConstants.restaurantname[itemNum], NMConstants.productinfo[itemNum], 
								"Distance : 3m",NMConstants.address[itemNum], bit, null, false));
					}
				} else {
					for (itemNum = 0; itemNum < NMConstants.totalListNum; itemNum++) {
						// imgutil.getPhoto(0, context,
						// thumbnailUrl_array.get(itemNum));
						// Bitmap bit = imgutil.mBit;
						Bitmap bit = BitmapFactory.decodeResource(
								getResources(), NMConstants.mImageIds[itemNum]);
	
						arItem.add(new TimeLineList(NMConstants.LIST_AB,
								NMConstants.restaurantname[itemNum], NMConstants.productinfo[itemNum], //add content
								"Distance : 3m",NMConstants.address[itemNum], bit, null, false));
					}
				}

				handler.sendEmptyMessage(0);

				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
			}
		});
		thread.start();
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			/*loagindDialog.dismiss();*/

			myAdapter = new TimeLineAdapter(context, arItem);  //TIMELINEADAPTER
			mainList = (ListView) findViewById(R.id.mainlist);

			mAddView.setVisibility(View.INVISIBLE);
			mainList.addFooterView(mAddView);

			if (UpdateFlag == 1) {
				myAdapter.notifyDataSetChanged();
			}
			mainList.setAdapter(myAdapter);
			// if(tokpo == 0) tokpo++; // TestLine
			// mainList.setSelectionFromTop(tokpo, 0); // 0326 Append, Good

			ListClick();
			mainList.setOnScrollListener(new OnScrollListener() {

				@SuppressWarnings("unchecked")
				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					// TODO Auto-generated method stub
					if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
						Log.v("nanum", "IN, totalItemCount = " + totalItemCount);

						if (NMConstants.totalListNum > itemNum) {
							mAddView.setVisibility(View.VISIBLE);
							new getMoreItems().execute(arItem);
						} else {
							mAddView.setVisibility(View.INVISIBLE);
						}

						Log.v("nanum", "IN END");
					}
				}

				@Override
				public void onScrollStateChanged(AbsListView view,
						int scrollState) {
					// TODO Auto-generated method stub

				}

			});
		}
	};

	public void ListClick() {  
		mainList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == NMConstants.totalListNum) {
					mainListUrl_A = "";

					// tokpo = position - 1;

					UpdateFlag = 1;
					createThreadAndDialog();

				} else {
					Intent intent = new Intent(TodayListAB_ngoc.this,
							TodayDetailView_ngoc.class);
					startActivity(intent);
				}
			}
		});
	}

	public void HttpPostTimeLine() {

		String getxml;
		DomParserUtil parser = new DomParserUtil();

		getxml = XMLUtil.getXml(""); // API 호출
		Log.e("nanum", "getxml = " + getxml);

		NodeList node = parser.getNodeList(parser.getDomElement(getxml), "");

		NMConstants.totalListNum += node.getLength();

	}

	private class getMoreItems extends
			AsyncTask<ArrayList<TimeLineList>, Integer, Long> {
		@Override
		protected Long doInBackground(ArrayList<TimeLineList>... params) {
			// TODO Auto-generated method stub
			Long result = 0L;

			if (NMConstants.totalListNum >= itemNum + 10) {
				int tmpEnd = itemNum + 10;

				Log.v("nanum", "if > itemNum = " + itemNum);
				// imgutil.getPhoto(0, context,
				// thumbnailUrl_array.get(itemNum));
				// Bitmap bit = imgutil.mBit;
			
		
				for (; itemNum < tmpEnd; itemNum++) {
					Bitmap bit = BitmapFactory.decodeResource(
							getResources(), NMConstants.mImageIds[itemNum]); //add the image...
					
					arItem.add(new TimeLineList(NMConstants.LIST_AB,
							NMConstants.restaurantname[itemNum], NMConstants.productinfo[itemNum], //add content
							"Distance : 3m",NMConstants.address[itemNum], bit, null, false));
				}
			} else {
				Log.v("nanum", "else ");
				// imgutil.getPhoto(0, context,
				// thumbnailUrl_array.get(itemNum));
				// Bitmap bit = imgutil.mBit;

				for (; itemNum < NMConstants.totalListNum; itemNum++) {
					Bitmap bit = BitmapFactory.decodeResource(
							getResources(), NMConstants.mImageIds[itemNum]); //add the image...
					
					arItem.add(new TimeLineList(NMConstants.LIST_AB,
							NMConstants.restaurantname[itemNum], NMConstants.productinfo[itemNum], //add content
							"Distance : 3m",NMConstants.address[itemNum], bit, null, false));
				}
			}
			Log.v("nanum", "changed!!");

			try {
				Thread.sleep(1000);
			} catch (Exception e) {
				;
			} // 1초 지연. 네트워크 작업 등을 시뮬레이션

			return null;
		}

		public void onPostExecute(Long result) {
			myAdapter.notifyDataSetChanged();

		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_LOCAL_AREA:
			return new AlertDialog.Builder(TodayListAB_ngoc.this)
					.setIcon(R.drawable.icon)
					.setTitle(R.string.local)
					.setSingleChoiceItems(R.array.local, 0,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									Log.e("nanum", "Choice whichButton = "
											+ whichButton);
									localPosition = whichButton;
								}
							})
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/*
									 * 확인 하면 다시 업데이트 시켜준다
									 */
								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked No so do some stuff */
								}
							}).create();
		case DIALOG_CATEGORY:
			return new AlertDialog.Builder(TodayListAB_ngoc.this)
					.setIcon(R.drawable.icon)
					.setTitle(R.string.local)
					.setSingleChoiceItems(R.array.category, 0,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									Log.e("nanum", "Choice whichButton = "
											+ whichButton);
									categoryPosition = whichButton;
								}
							})
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/*
									 * 확인 하면 다시 업데이트 시켜준다
									 */
								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked No so do some stuff */
								}
							}).create();
		case DIALOG_SEARCH:
			// This example shows how to add a custom layout to an AlertDialog
			LayoutInflater factory = LayoutInflater.from(this);
			final View textEntryView = factory.inflate(R.layout.dialogsearch,
					null);
			return new AlertDialog.Builder(TodayListAB_ngoc.this)
					.setIcon(R.drawable.icon)
					.setTitle(R.string.search)
					.setView(textEntryView)
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked OK so do some stuff */
								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked cancel so do some stuff */
								}
							}).create();
		}
		return super.onCreateDialog(id);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_location:
	//		showDialog(DIALOG_LOCAL_AREA); // 지역설정
			Intent intent1 = new Intent(TodayListAB_ngoc.this, TodayLocationCity_ngoc.class);
			startActivityForResult(intent1,  DIALOG_LOCAL_AREA);
			break;
		case R.id.btn_title:
			Intent intent2 = new Intent(TodayListAB_ngoc.this, TodayCategory.class);// 카테고리, TodayCategory라는 Activity Class 추가해 준 후 Intent로 넘겨서 결과 받고 정렬 ㄱㄱㄱ
			startActivityForResult(intent2,  DIALOG_CATEGORY);
			break;
		case R.id.btn_search:
			Intent intent = new Intent(TodayListAB_ngoc.this, TodaySearch.class);
			startActivityForResult(intent, DIALOG_SEARCH);
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//상단 버튼 클릭을 통해서 정보 새로 Renewal 하는 곳
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode){
		
		case DIALOG_LOCAL_AREA:
			if(resultCode == RESULT_OK){
				loc_selected = data.getStringExtra("LOC_SELECTED");
				Log.e("nanum","search = "+loc_selected);
			}
			break;
		case DIALOG_CATEGORY:
			if(resultCode == RESULT_OK){
				cate_selected = data.getStringExtra("CATE_SELECTED");
				Log.e("nanum","search = "+cate_selected);
				Bitmap bit = BitmapFactory.decodeResource(getResources(), NMConstants.mImageIds[itemNum]);
				arItem.set(0, new TimeLineList(NMConstants.LIST_AB,
				NMConstants.restaurantname[itemNum], NMConstants.productinfo[itemNum], //add content
				"Distance : 5m",NMConstants.address[itemNum], bit, null, false));
			}
			break;
		
		case DIALOG_SEARCH:
			if(resultCode == RESULT_OK){
				searchStr = data.getStringExtra("SEARCH");
				Log.e("nanum","search = "+searchStr);
			}
			break;
		}
		
	}

}
